package com.lss.Filter;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 过滤器，过滤请求，如果没有登录，就重定向到登录页面
 */
public class MyWebControllerFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session，然后获取login
        HttpSession session = request.getSession();
        Object login = session.getAttribute("login");
        //login对象不为空则为登录过的
        if (login != null) {
            return true;
        }
        //未登录，直接拦截
        session.setAttribute("msg", "请先登录");
        //转发到首页
        //request.getRequestDispatcher("/").forward(request,response);

        //重定向到登录页面
        response.sendRedirect("/login");
        return false;
    }
}
